package io.github.lee.app.unsplash.ui.search

import android.content.Context
import android.content.Intent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.activity.viewModels
import androidx.appcompat.widget.Toolbar
import androidx.databinding.ViewDataBinding
import com.gyf.immersionbar.ktx.immersionBar
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.R
import io.github.lee.app.unsplash.databinding.ToolbarSearchBinding
import io.github.lee.app.unsplash.ui.search.history.SearchHistoryFragment
import io.github.lee.app.unsplash.ui.search.result.SearchResultFragment
import io.github.lee.core.ui.BaseActivity

@AndroidEntryPoint
class SearchActivity : BaseActivity<ViewDataBinding, SearchVM>() {

    private val toolbarVB by lazy {
        ToolbarSearchBinding.inflate(layoutInflater)
    }
    private val searchHistoryFragment by lazy {
        SearchHistoryFragment.newInstance().also {
            it.searchVM = vm
        }
    }

    private val searchResultFragment: SearchResultFragment by lazy {
        SearchResultFragment.newInstance()
    }

    //===Desc:======================================================================================
    companion object {
        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, SearchActivity::class.java)
            context.startActivity(starter)
        }
    }

    //===Desc:======================================================================================

    override fun onCreateViewModel(): SearchVM =
        viewModels<SearchVM>().value

    //===Desc:======================================================================================
    override fun onCreateToolbar(): Toolbar =
        toolbarVB.toolbar

    //===Desc:======================================================================================

    override fun onObserved() {
        super.onObserved()

        vm?.apply {
            showSearchClear.observe(this@SearchActivity) {
                toolbarVB.showClear = it
            }
            cancelClicked.observe(this@SearchActivity) {
                if (it) {
                    finish()
                }
            }

            hideKeyboard.observe(this@SearchActivity) {
                if (it) {
                    toolbarVB.etInputKeyWord.clearFocus()
                    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(toolbarVB.etInputKeyWord.windowToken, 0)
                }else{
                    toolbarVB.etInputKeyWord.requestFocus()
                    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.showSoftInput(toolbarVB.etInputKeyWord, 0)

                }
            }
        }
    }

    override fun onSetViewListener() {
        super.onSetViewListener()

        toolbarVB.etInputKeyWord.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                showHistory(true)
            } else {
                showHistory(false)
                searchResultFragment.search(vm?.searchKeyWord?.get())
            }
        }
        toolbarVB.etInputKeyWord.setOnEditorActionListener { _, actionId, _ ->
            if (actionId != EditorInfo.IME_ACTION_SEARCH) {
                return@setOnEditorActionListener false
            }
            if (vm?.searchKeyWord?.get().isNullOrEmpty()) {
                toast(getString(R.string.hint_search))
                return@setOnEditorActionListener false
            }
            vm?.saveSearchKeyword()
            true

        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        immersionBar {
            statusBarColor(R.color.mainBackground)
            statusBarDarkFont(false)
            fitsSystemWindows(true)
        }
        toolbarVB.vm = vm
        supportFragmentManager.beginTransaction()
            .add(contentFrameLayout.id, searchHistoryFragment)
            .add(contentFrameLayout.id, searchResultFragment)
            .show(searchHistoryFragment)
            .hide(searchResultFragment)
            .commitNowAllowingStateLoss()
        contentFrameLayout.visibility = View.VISIBLE
    }

    private fun showHistory(show: Boolean) {

        val t = supportFragmentManager.beginTransaction()
        if (show) {
            t.show(searchHistoryFragment)
                .hide(searchResultFragment)
        } else {
            t.show(searchResultFragment)
                .hide(searchHistoryFragment)

        }
        t.commitNowAllowingStateLoss()

    }
}